package com.meila.cms.services.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.meila.cms.model.CarDesignModel;
import com.meila.cms.services.IFileService;
import com.meila.cms.util.config.Property;
 
@Service
public class FileService extends BaseService implements IFileService {

	@Override
	public void getFile(String dirname, String username, String type,
			String year, String month, String picname, String extname,
			HttpServletRequest request, HttpServletResponse response) {
		    
		    // TODO Auto-generated method stub
		    String BASE_FILEUPLOAD_PATH= Property.getProperty("BASE_FILEUPLOAD_PATH");
		   
		    WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();  
	        ServletContext application = webApplicationContext.getServletContext();

			String web_path = application.getRealPath("").replace("\\", "/");
	 
	        BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("username",username);
	    	BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("type", "A0");
	    	BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("year", year);
	    	BASE_FILEUPLOAD_PATH=BASE_FILEUPLOAD_PATH.replace("month",month);
	    	
			String fullPath = web_path+"/"+BASE_FILEUPLOAD_PATH +picname+"."+extname;
			
			response.setHeader("Cache-Control", "max-age=10000000");
			InputStream in = null;
			OutputStream out = null;
			try {
				File file = new File(fullPath);
				if (!file.isFile()) {
					 
				}
				in = new FileInputStream(file);
				int len = 0;
				byte[] buffer = new byte[1024];
				out = response.getOutputStream();
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (Exception e) {
						throw new RuntimeException(e);
					}

				}
			}
	}

	/**
	 * 存在数据库的html图片采用相对路径
	 */
	@Override
	public void kindeditorContent(int designid,Model model) {
		
		// TODO Auto-generated method stub
		CarDesignModel carDesignModel=carDesignMapper.selectByPrimaryKey(designid);
		
		
		try {
			
			//model.addAttribute("content",new String(carDesignModel.getCarsidelogo(),"UTF-8"));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		model.addAttribute("content", carDesignModel.getCarsidelogo());
		
	}

 
 
 
}
